import { Server } from "socket.io"

export const corsOptions = {
    origin: ["http://localhost:5173"],
    methods: ["GET", "POST"]
}

export class CreateSocket {
	io = null;
	socket = null;
	userId = '';

	constructor(_socket, _io, _userId) {
		this.socket = _socket;
		this.io = _io;
		this.userId = _userId

		this.socket.join(this.userId);
		this.io.to(this.userId).emit('reviceConnect', '您连接了 socket');
		this.socket.on('sendMsg', this.sendMsg);
		this.socket.on('disconnect', this.disconnected);
	}

	sendMsg(data = {}, msgType = 'reviceMsg', list) {
		switch(msgType) {
			// 通知用户有人添加你为好友
			case 'friendRequest':
				const { to: userId } = data
				this.io.to(userId).emit(msgType, list);
				break
			default: 
				const { msgFrom, msgTo, roomId } = data;
				this.io.to(roomId).emit(msgType, {
					...data,
					detail: `${msgFrom} 在 ${roomId} 房间发送了一条消息`,
				});
				break
		}
	}

	disconnected(reason) {
		console.log('disconnect');
	}
}

export const socketMap = {};

export const handleSocket = (httpServer) => {
	const io = new Server(httpServer, {
		// 配置跨域
		cors: corsOptions,
	});
	io.on('connection', (_socket) => {
		const { userId } = _socket.handshake.query;
		const socket = new CreateSocket(_socket, io, userId)
		socketMap[userId] = socket
	});
} 